package com.sztx.pay.center.dataaccess.dao.redis.impl;

import java.util.Collection;






import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.stereotype.Repository;

import com.sztx.pay.center.dataaccess.dao.redis.UserRedisDAO;
import com.sztx.se.dataaccess.redis.callback.RedisCallback;
import com.sztx.se.dataaccess.redis.impl.BaseRedisDAOImpl;

@Repository("userRedisDAO")
public class UserRedisDAOImpl extends BaseRedisDAOImpl implements UserRedisDAO {
	private static Logger logger = LoggerFactory.getLogger(UserRedisDAOImpl.class);
	
	public static String GRAY_USER_KEY = "paycenter:user_gray:set";
	public static final long EXPIRE_TIME_ORDER = 60*60*24*60l;   //60天
	
	@Override
	public boolean addGrayUser(final String userId) {
		
		return redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public String getKey() {
				return GRAY_USER_KEY;
			}

			@Override
			public Boolean doInRedis(RedisConnection connection, byte[] key) {				
				try {
					logger.debug("将用户{}增加到灰度", userId);
					long res = connection.sAdd(key, serialize(userId));
					logger.debug("将用户{}增加到灰度结果{}", userId, res);
				} catch (Exception e) {
					logger.error("添加用户"+userId+"失败", e);
					return false;
				}				
				return true;
			}
		});	
	}

	@Override
	public boolean isGrayUser(final String userId) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public String getKey() {
				return GRAY_USER_KEY;
			}

			@Override
			public Boolean doInRedis(RedisConnection connection, byte[] key) {								
				return connection.sIsMember(key, serialize(userId));				
			}
		});	
	}

	@Override
	public boolean syncGrayUser(final Collection<String> users) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public String getKey() {
				return GRAY_USER_KEY;
			}

			@Override
			public Boolean doInRedis(RedisConnection connection, byte[] key) {			
				if (users == null || users.isEmpty()) {
					return true;
				}				
				int size = users.size();				
				byte[][] data = new byte[size][];
				
				int i = 0;
				for (String userId : users) {					
					data[i++] = serialize(userId);
				}	
				
				connection.expire(key, EXPIRE_TIME_ORDER);				
				connection.sAdd(key, data);

				return true;
			}
		});
	}

	@Override
	public boolean rmoveGrayUser(final String userId) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public String getKey() {
				return GRAY_USER_KEY;
			}

			@Override
			public Boolean doInRedis(RedisConnection connection, byte[] key) {								
				logger.debug("将用户{}删除灰度", userId); 
				long res = connection.sRem(key, serialize(userId));				 
				logger.debug("将用户{}删除灰度结果{}", userId, res);
				return true;
			}
		});	
	}

}
